package com.wrb.coupon.service;

import com.wrb.coupon.exception.ServiceException;
import com.wrb.coupon.mapper.CouponCustomerMapper;
import com.wrb.coupon.model.CouponCustomer;
import com.wrb.coupon.response.ResponseCode;
import com.wrb.coupon.utils.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author wrb
 * @date 2019/12/4 11:39
 */
@Service
public class CouponService {

	@Autowired
	private CouponCustomerMapper couponCustomerMapper;

	public String generateCustomerCoupon(long customerId, long couponTemplateId, String source) throws ServiceException {
		CouponCustomer couponCustomer = new CouponCustomer();
		couponCustomer.setCouponId(SnowflakeIdWorker.generateId());
		couponCustomer.setCouponTemplateId(couponTemplateId);
		couponCustomer.setCustomerId(customerId);
		couponCustomer.setSource(source);
		couponCustomer.setStatus(1);
		String code = UUID.randomUUID().toString();
		couponCustomer.setCode(code);
		int result = this.couponCustomerMapper.insertSelective(couponCustomer);
		if (result == 0) {
			throw new ServiceException(ResponseCode.DB_ERROR, "发放用户优惠券失败");
		}
		return code;
	}

}
